package com.king.headline.util.encry;

import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;


public class CryptoUtil {

    public static String encrypt(String text) {
    	try {
			return DesEncrypter.getInstance().encrypt(text);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
        //return encrypt(text, DEFAULT_KEY);
    }

    public static String encrypt(String text, String key) throws EncryptionException {
    	try {
			return DesEncrypter.getInstance().encrypt(text, key);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}    	
    }

    public static String decrypt(String text) throws EncryptionException {
    	try {
			return DesEncrypter.getInstance().decrypt(text);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
    }

    public static String decrypt(String text, String key) throws EncryptionException {
    	try {
			return DesEncrypter.getInstance().decrypt(text, key);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}    	
    }

    /**
     * Description: This method is used to encode the parameters with special characters: '=', '+','-', '&',....
     * @param str
     * @return encoded String
     * @throws Exception
     */
    public static String encryptId(long id){
        try {
            return URLEncoder.encode(encrypt(id + ""), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * Description: This method is used to decrypt the parameter with special characters.
     * @param str
     * @return Decoded String
     * @throws Exception
     */
    public static long decryptId(String str){
      try {
            String id = URLDecoder.decode(decrypt(str), "UTF-8"); 
            return  Long.parseLong(id); 
        } catch (Exception e) {
            e.printStackTrace();
        }
        return -1;   
    }
    
    public static String getMD5(String msg){
    	try {
    		MessageDigest m = MessageDigest.getInstance("MD5");
    		m.update(msg.getBytes());
    		byte[] digest = m.digest();
    		BigInteger bigInt = new BigInteger(1,digest);
    		String hashtext = bigInt.toString(16);
    		while(hashtext.length() < 32 ){
    		  hashtext = "0"+hashtext;
    		}
    		return hashtext;
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
			return null;
		}    	
    }
	            
}
